import redis,flask,json,hashlib,pymysql,traceback,time

MYSQL_INFO = {
    'host':'118.24.3.40',
    'user':'jxz',
    'password':'123456',
    'db':'jxz',
    'charset':'utf8',
    'autocommit':True
}#建立连接数据库信息常量
r = redis.Redis(host='118.24.3.40',
                password='HK139bc&*',
                port='6379',
                db=4,
                decode_responses=True#默认redis返回的结果是字符串
)#建立连接redis常量

def md5(s): #md5加密函数
    s = str(s)
    s = s.encode()  # 字符串转成bytes类型
    m = hashlib.md5(s)  # 加密,必须是bytes类型,结果是ASCII码，加密后不可逆
    result = m.hexdigest()  # 返回十六进制数据字符串值
    return result

def execute_sql(sql):#执行sql函数
    conn = pymysql.connect(**MYSQL_INFO)#连接数据库
    cur = conn.cursor(pymysql.cursors.DictCursor)#建立游标,查询结果以字典格式输出

    try:
        cur.execute(sql)
    except:
        print('sql不正确')
        traceback.print_exc()#打印报错信息
    else:
        return cur.fetchall()  #返回sql查询出的结果
    finally:
        conn.close()
        cur.close()#关闭数据库连接

def redis(key,value):
    r.set(key,value)
    h_expire_time = 60*60*24 #设置过期时间
    expire_time = r.expire(key,h_expire_time)
    return expire_time



server = flask.Flask(__name__)
@server.route('/login', methods=['post'])
def login():
    username = flask.request.values.get('username','')
    password = flask.request.values.get('password','')

    if username.strip() and password.strip():
        query_sql = 'select * from app_myuser where username = "%s" AND password = "%s";'%(username,password)

        if execute_sql(query_sql):
            sessionid = md5(time.time()) + '_' + username #存储sessionid,时间戳做md5加密
            r.set(sessionid, username)#往redis里存数据
            h_expire_time = 60 * 60 * 24  # 设置过期时间
            r.expire(sessionid, h_expire_time)# 设置过期时间

            return json.dumps({'code': '0', 'msg': '登录成功','sessionid':sessionid},ensure_ascii=False)
        else:
            return json.dumps({'code': '-1', 'msg': '输入的用户名/密码错误'})
    else:
        return json.dumps({'code': '-1', 'msg': '不能为空'})


server.run(host='127.0.0.1',port=8888,debug=True)
